//
//  SafePatrolViewController.m
//  Estate
//
//  Created by wangdongdong on 2017/9/29.
//  Copyright © 2017年 ttsx. All rights reserved.
//

#import "ActionSheetDatePicker.h"
#import "SafePatrolModel.h"
// 单行输入cell
#import "QianDTableCell.h"
// 多行输入cell
#import "B_wuLiaoCell.h"

#import "SafePatrolViewController.h"

@interface SafePatrolViewController ()<UITableViewDelegate, UITableViewDataSource>

// 表格
@property (strong, nonatomic) TPKeyboardAvoidingTableView *tableView;

// 数据
@property (strong, nonatomic) SafePatrolModel *patralModel;

// 施工责任人数据
@property (strong, nonatomic) NSMutableArray *constructionContractorArr;
// 施工单位ID
@property (copy, nonatomic) NSString *constructionUnitID;

@end


@implementation SafePatrolViewController

// 施工责任人数据
- (NSMutableArray *)constructionContractorArr {
    if (!_constructionContractorArr) {
        _constructionContractorArr = [NSMutableArray array];
    }
    return _constructionContractorArr;
}

// 数据
- (SafePatrolModel *)patralModel {
    if (!_patralModel) {
        _patralModel = [[SafePatrolModel alloc] init];
    }
    return _patralModel;
}

- (TPKeyboardAvoidingTableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT - 188) style:UITableViewStylePlain];
        _tableView.backgroundColor = UIColorFromRGB(0xf2f2f2);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        [_tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"qCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"bCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    [self.view addSubview:self.tableView];
    
    // 选择施工单位后, 刷新施工责任人
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTable:) name:@"refreshCheckInformation" object:nil];
}

// 添加通知(暂存/保存检查信息)
- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveSupervisionSafetyInspection:) name:@"saveSafeCheck" object:nil];
}

// 移除通知(暂存/保存检查信息)
- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"saveSafeCheck" object:nil];
}

// 刷新表格
- (void)refreshTable:(NSNotification *)notification {
    self.constructionUnitID = [notification object];
    if (self.constructionUnitID) {
        // 查找施工责任人数据
        [self checkConstructionContractor];
    }
}

// 查找施工责任人数据
- (void)checkConstructionContractor {
    // 初始化数据源
    [self.constructionContractorArr removeAllObjects];
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM PROJECT_USER WHERE PRO_ID = '%@' AND UNIT_ID = '%@' AND USER_TYPE IN ('CONSTRACT_01', 'CONSTRACT_02', 'CONSTRACT_03', 'CONSTRACT_04', 'CONSTRACT_05', 'CONSTRACT_06', 'CONSTRACT_07', 'CONSTRACT_09')", PROID, self.constructionUnitID];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    FMResultSet *result = [db executeQuery:sqlStr];
    while ([result next]) {
        NSMutableDictionary *mDic = [NSMutableDictionary dictionary];
        
        // 用户ID
        NSString *userID = [result stringForColumn:@"USER_ID"];
        [mDic setObject:userID forKey:@"USER_ID"];
        // 用户真实姓名
        NSString *realName = [LSUtility getuserIdByUserName:userID][@"REAL_NAME"];
        [mDic setObject:realName forKey:@"REAL_NAME"];
    
        [self.constructionContractorArr addObject:mDic];
    }
    [db close];
}

#pragma mark - 提交保存监理安全巡查
- (void)saveSupervisionSafetyInspection:(NSNotification *)notification {
    // 接收通知来的信息
    NSDictionary *parameDic = [notification object];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    // 字段及对应值
    NSDictionary *pragameDic = [NSDictionary dictionary];
    pragameDic = @{
                   @"ID":DEFISNUL([NSUUID UUID].UUIDString),
                   @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                   @"BASIC_RECORD_ID":DEFISNUL(parameDic[@"safeBaseID"]),
                   @"RECORD_USER":DEFISNUL(DEF_PERSISTENT_GET_OBJECT(@"userid")),
                   @"RECORD_TYPE":DEFISNUL(@"SAFE_RECORD_01"),
                   @"RECORD_TITLE":DEFISNUL(parameDic[@"title"]),
                   @"RECORD_NUMBER":DEFISNUL(parameDic[@"recordNumber"]),
                   @"DANGER_FACTOR":DEFISNUL(self.patralModel.hiddenTrouble),
                   @"DEAL_OPINION":DEFISNUL(self.patralModel.dealOpinion),
               @"CONSTRUCT_RESPONSIBLE_PERSON_USER_ID":DEFISNUL(self.patralModel.constructionContractorId),
               @"CONSTRUCT_RESPONSIBLE_PERSON_REALNAME":DEFISNUL(self.patralModel.constructionContractorRealName),
                   @"REVIEW_TIME":DEFISNUL(self.patralModel.reviewTime),
                   @"RECIFY_AND_REFORM_INFO":DEFISNUL(self.patralModel.rectificationImplementation),
                   @"REVIEW_OPINION":DEFISNUL(self.patralModel.reviewOpinion),
                   @"EXTEND_INFO":@"",
                   @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"loginuser"),
                   @"CREATE_TIME":DEFISNUL([LSUtility nowTime]),
                   @"CREATE_IP":DEFISNUL([LSUtility getIPAddress]),
                   @"MODIFY_USER_NAME":@"",
                   @"MODIFY_TIME":@"",
                   @"MODIFY_IP":@"",
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"ADD",
                   };
    
    BOOL isAdd = [dbhelper DataBase:db insertKeyValues:pragameDic intoTable:SECURITY_PATROL];
    if (isAdd) {
        NSLog(@"添加监理安全巡查成功");
        
    } else {
        NSLog(@"添加监理安全巡查失败");
    }
    
    // 刷新安全列表页
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshSafeList" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma MARK - UITableViewDelegate, UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger row = indexPath.row;
    if (row == 0 || row == 1 || row == 4 || row == 5) {
        return 120;
        
    } else {
        return 50;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    NSInteger row = indexPath.row;
    if (row == 0 || row == 1 || row == 4 || row == 5) {
        B_wuLiaoCell *bCell = [tableView dequeueReusableCellWithIdentifier:@"bCell" forIndexPath:indexPath];

        if (row == 0) {
            bCell.title.text = @"隐患或危险因数描述:";
            bCell.text.placeholder = @"请输入隐患或危险因数描述";
            if (self.patralModel.hiddenTrouble && ![self.patralModel.hiddenTrouble isEqualToString:@""]) {
                bCell.text.text = self.patralModel.hiddenTrouble;
            }
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.patralModel.hiddenTrouble = valueStr;
            };
            
        } else if (row == 1) {
            bCell.title.text = @"处理意见:";
            bCell.text.placeholder = @"请输入处理意见";
            if (self.patralModel.dealOpinion && ![self.patralModel.dealOpinion isEqualToString:@""]) {
                bCell.text.text = self.patralModel.dealOpinion;
            }
        
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.patralModel.dealOpinion = valueStr;
            };
        } else if (row == 4) {
            bCell.title.text = @"整改落实情况:";
            bCell.text.placeholder = @"请输入整改落实情况";
            if (self.patralModel.rectificationImplementation && ![self.patralModel.rectificationImplementation isEqualToString:@""]) {
                bCell.text.text = self.patralModel.rectificationImplementation;
            }
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.patralModel.rectificationImplementation = valueStr;
            };
            
        } else if (row == 5) {
            bCell.title.text = @"复查意见:";
            bCell.text.placeholder = @"请输入复查意见";
            if (self.patralModel.reviewOpinion && ![self.patralModel.reviewOpinion isEqualToString:@""]) {
                bCell.text.text = self.patralModel.reviewOpinion;
            }
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.patralModel.reviewOpinion = valueStr;
            };
        }
        return bCell;
        
    } else {
        QianDTableCell *qianCell = [tableView dequeueReusableCellWithIdentifier:@"qCell" forIndexPath:indexPath];
        qianCell.textField.layer.borderColor = [[UIColor colorWithRed:215.0 / 255.0 green:215.0 / 255.0 blue:215.0 / 255.0 alpha:1] CGColor];
        qianCell.textField.layer.borderWidth = 0.6f;
        qianCell.textField.layer.cornerRadius = 6.0f;
        qianCell.textField.enabled = NO;
        
        if (row == 2) {
            qianCell.title.text = @"施工责任人";
            qianCell.textField.text = @"请选择施工责任人";
            if (self.patralModel.constructionContractorRealName && ![self.patralModel.constructionContractorRealName isEqualToString:@""]) {
                qianCell.textField.text = self.patralModel.constructionContractorRealName;
                
            }
        } else {
            qianCell.title.text = @"复查日期";
            qianCell.textField.placeholder = @"请选择复查日期";
            if (self.patralModel.reviewTime && ![self.patralModel.reviewTime isEqualToString:@""]) {
                qianCell.textField.text = self.patralModel.reviewTime;
            }
        }
        return qianCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    if (row == 2) {
        // 项目负责人真实姓名
        if (self.constructionContractorArr.count > 0) {
            NSMutableArray *realNameArr = [NSMutableArray array];
            for (NSDictionary *dic in self.constructionContractorArr) {
                [realNameArr addObject:dic[@"REAL_NAME"]];
            }
            NSNumber *ninit = [NSNumber numberWithInteger:0];
            [ActionSheetStringPicker showPickerWithTitle:nil rows:@[realNameArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray *selectedIndex, NSArray *selectedValue) {
                
                // 修改数据
                QianDTableCell *qianCell = [tableView cellForRowAtIndexPath:indexPath];
                qianCell.textField.text = [selectedValue firstObject];
                
                // 保存项目负责人数据
                NSInteger index = [[selectedIndex firstObject] integerValue];
                NSDictionary *constructionUnitDic = self.constructionContractorArr[index];
                self.patralModel.constructionContractorId = constructionUnitDic[@"USER_ID"];
                self.patralModel.constructionContractorRealName = constructionUnitDic[@"REAL_NAME"];
                
            } cancelBlock:nil origin:self.view];
            
        } else {
            if (self.constructionUnitID && ![self.constructionUnitID isEqualToString:@""]) {
                [LSUtility showToastWithMessage:@"项目负责人数据为空" inView:self.view Andtime:1.0];

            } else {
                [LSUtility showToastWithMessage:@"请先选择施工单位" inView:self.view Andtime:1.0];
            }
        }
    } else if (row == 3) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate *date = [NSDate date];
        
        ActionSheetDatePicker *picker = [[ActionSheetDatePicker alloc] initWithTitle:nil datePickerMode:UIDatePickerModeDate selectedDate:date doneBlock:^(ActionSheetDatePicker *picker, NSDate *selectedDate, id origin) {
            
            NSString *dateStr = [dateFormatter stringFromDate:selectedDate];
            dateStr = [dateStr substringToIndex:10];
            // 修改数据
            QianDTableCell *qianCell = [tableView cellForRowAtIndexPath:indexPath];
            qianCell.textField.text = dateStr;
            self.patralModel.reviewTime = dateStr;
            
        } cancelBlock:nil origin:self.view];
        [picker showActionSheetPicker];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

